package org.unique.support.orm;

import java.util.List;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unique.aop.ProxyBeanFactory;
import org.unique.ioc.AbstractBeanFactory;
import org.unique.ioc.annotation.Service;
import org.unique.ioc.impl.SingleBean;
import org.unique.support.Support;
import org.unique.support.orm.connection.ConnectionManager;
import org.unique.support.orm.tx.TransactionInterceptor;

/**
 * Object Relational Mapping
 * @author biezhi
 * @version 1.0
 */
public class OrmSupport extends Support {

	private static final Logger LOGGER = LoggerFactory.getLogger(OrmSupport.class);
	
	private AbstractBeanFactory beanFactory = new SingleBean();
	
	@Override
	public void startup() {
		DataSource dataSource = ConnectionManager.getDataSource();
		if(null != dataSource){
			TransactionInterceptor tr = new TransactionInterceptor(dataSource);
			List<Object> services = beanFactory.getBeansByAnnotation(Service.class);
			if(null != services){
				for(Object obj : services){
					ProxyBeanFactory.single().newProxy(obj, tr);
//					Object proxy = ProxyBeanFactory.single().newProxy(obj, tr);
//					System.out.println("startup proxy=" + proxy);
//					System.out.println("startup proxy=" + obj);
//					beanFactory.resetBean(obj.getClass(), proxy);
				}
			}
		} else{
			LOGGER.warn("事务开启失败，DataSource为空！");
		}
		LOGGER.info("orm增强加载成功");
		this.status = 1;
	}
	
	@Override
	public void shutdown() {
		this.status = 0;
	}
	
}
